import axios from 'axios';
import type { AxiosInstance, AxiosResponse } from 'axios';
import { tipSuccess, tipFailure } from "@/utils/tips"

const instance: AxiosInstance = axios.create({
    baseURL: '/api',
    timeout: 1000,
});

instance.interceptors.request.use(
    (config) => {

    const token: string = localStorage.getItem('token') || '';

    if (config != null) {
        config.headers['token'] = token;
    }

    return config;
}, (error) => {
    tipFailure('请求错误')
    return Promise.reject(error);
});

instance.interceptors.response.use(
    (response: AxiosResponse) => {
        const res = response.data

        // 如果返回的状态码不是200，则判断为错误
        if (res.code !== 200) {
            tipFailure(res.msg || '系统错误')
            return Promise.reject()
        } else {
            return res
        }

    }, (error) => {
        tipFailure('响应错误')
        return Promise.reject(error);
    });

export function get<T>(url: string, params?: any): Promise<T> { 
    return instance.get(url, { params });
}

export function post<T>(url: string, data?: any): Promise<T> {
    return instance.post(url, data);
}

export function put<T>(url: string, data?: any, config?: any): Promise<T> {
    return instance.put(url, data, config);
}

export function del<T>(url: string, params?: any): Promise<T> {
    return instance.delete(url, { params });
}
